﻿$.fn.dataGrid = function (options) {
    var defaults = {
        datatype: "json",
        autowidth: true,
        rownumbers: true,
        shrinkToFit: false,
        gridview: true
    };
    var options = $.extend(defaults, options);
    var $element = $(this);
    $element.jqGrid(options);
};
$.fn.isScroll = function () {
    var $element = $(this);
    var isScroll = false;
    $element.scrollTop(10);//控制滚动条下移10px
    if ($element.scrollTop() > 0) {
        isScroll = true;
        //alert("有滚动条");
    } else {
        isScroll = false;
        //alert("没有滚动条");
    }
    $element.scrollTop(0);//滚动条返回顶部
    return isScroll;
};
$.fn.setScrollTop = function(rowLength, currRowIndex){
    var $element = $(this);
    if ($element.isScroll()) {
        var height = $element.height();
        var scrollHeight = $element[0].scrollHeight;
        var rowHeight = parseInt(scrollHeight / rowLength);
        var showRows = parseInt(height / rowHeight);
        var showRowsMiddel = parseInt(height / rowHeight / 2);
        //alert(height + ' ' + scrollHeight + ' ' + rowHeight + ' ' + showRows + ' ' + showRowsMiddel);
        if (currRowIndex <= showRowsMiddel) {
            //alert("不用滚动");
            $element.scrollTop(0);
        } else {
            //alert("用滚动");
            var allScrollTop = scrollHeight - height + 18;
            var currScrollTop = (currRowIndex - showRowsMiddel) * rowHeight;
            if (currScrollTop > allScrollTop) {
                currScrollTop = allScrollTop;
            }
            $element.scrollTop(currScrollTop);
            //$grid.scrollTop();//滚动条
        }
    }
};
$.fn.bindSelect2 = function (options) {
    var defaults = {
        id: "id",
        text: "text",
        value: undefined,
        search: true,
        url: "",
        param: [],
        change: null,
        async: false
    };
    var options = $.extend(defaults, options);
    var $element = $(this);
    if (options.url != "") {
        $.ajax({
            url: options.url,
            data: options.param,
            dataType: "json",
            async: options.async,
            success: function (data) {
                $.each(data, function (i) {
                    var jsonStr = JSON.stringify(data[i]);
                    $element.append($("<option></option>").val(data[i][options.id]).html(data[i][options.text]).attr("obj", jsonStr));
                });
                if (!!options.value) {
                    $element.val(options.value);
                }
                $element.select2({
                    minimumResultsForSearch: options.search == true ? 0 : -1
                });
                $element.on("change", function (e) {
                    if (options.change != null) {
                        options.change(data[$(this).find("option:selected").index()]);
                    }
                    $("#select2-" + $element.attr('id') + "-container").html($(this).find("option:selected").text().replace(/　　/g, ''));
                });
            }
        });
    } else {
        $element.select2({
            //minimumResultsForSearch: -1
            minimumResultsForSearch: options.search == true ? 0 : -1
        });
    }
}

$.fn.formValid = function () {
    return $(this).valid({
        errorPlacement: function (error, element) {
            element.parents('.formValue').addClass('has-error');
            element.parents('.has-error').find('i.error').remove();
            element.parents('.has-error').append('<i class="form-control-feedback fa fa-exclamation-circle error" data-placement="left" data-toggle="tooltip" title="' + error + '"></i>');
            $("[data-toggle='tooltip']").tooltip();
            var parentLeft = element.parents('.formValue').offset().left;
            var parentWidth = element.parents('.formValue').width();
            var selfLeft = element.offset().left;
            var selfWidth = element.width();
            var currRight = (parentWidth - selfWidth) + (parentLeft - selfLeft);
            //alert(currRight);
            element.parents('.has-error').find('i.error').css('top', '0px');
            element.parents('.has-error').find('i.error').css('right', (currRight - 18) + 'px');
            //alert(selfWidth);
            //alert(element.hasClass("select2-hidden-accessible"));
            if (element.hasClass("select2-hidden-accessible")) {
                element.parents('.has-error').find('i.error').css('top', '-1px');
                var selfWidth2 = element.next().width();
                element.parents('.has-error').find('i.error').css('right', (currRight - selfWidth2 - 14) + 'px')
            }
            if (element.parents('.input-group').hasClass('input-group')) {
                element.parents('.has-error').find('i.error').css('right', '33px')
            }
        },
        success: function (element) {
            element.parents('.has-error').find('i.error').remove();
            element.parent().removeClass('has-error');
        }
    });
}
function hackHeight(listId) {
    $(listId + '_frozen tr').slice(1).each(function () {

        var rowId = $(this).attr('id');

        var frozenTdHeight = parseFloat($('td:first', this).height());
        var normalHeight = parseFloat($(listId + ' #' + $(this).attr('id')).find('td:first').height());
        // 如果冻结的列高度小于未冻结列的高度则hack之
        if (frozenTdHeight < normalHeight) {

            $('td', this).each(function () {

                /*
				 浏览器差异高度hack
				 */
                var space = 5; 
                if (/webkit/.test(navigator.userAgent.toLowerCase())) {
                    space = 6;
                } else if (/firefox/.test(navigator.userAgent.toLowerCase())) {
                    //space = 6;
                }

                if (!$(this).attr('style') || $(this).attr('style').indexOf('height:') == -1) {
                    $(this).attr('style', $(this).attr('style') + ";height:" + (normalHeight + space) + "px !important");
                }
            });
        }
    });
}

function lockInputById(id) {
    if (id != '') { id = id + ' '; }
    $(id + 'input[type="text"]').prop("disabled", true);
    $(id + 'textarea').prop("disabled", true);
    $(id + 'select').prop("disabled", true);
    $(id + 'input[type="radio"]').prop("disabled", true);
    $(id + 'input[type="checkbox"]').prop("disabled", true);
}

function emptyDataById(id) {
    if (id != '') { id = id + ' '; }
    $(id + 'input[type="text"]').val("");
    $(id + 'input[type="hidden"]').val("");
    $(id + 'textarea').val("");
    $(id + 'select').val("");
    $(id + 'input[type="radio"]').prop("checked", false);
    $(id + 'input[type="checkbox"]').prop("checked", false);
}

function setDataByJson(id, data, prefix) {
    if (data == null) { return; }
    if (id != '') { id = id + ' '; }
    prefix = prefix || '';
    $(id + 'input[type=text]').each(function () {
        var currId = this.id.replace(prefix, "");
        if (data.hasOwnProperty(currId)) {
            $('#' + this.id).val(data[currId]);
        }
    });
    $(id + 'input[type=hidden]').each(function () {
        var currId = this.id.replace(prefix, "");
        if (data.hasOwnProperty(currId)) {
            $('#' + this.id).val(data[currId]);
        }
    });
    $(id + 'select').each(function () {
        var currId = this.id.replace(prefix, "");
        if (data.hasOwnProperty(currId)) {
            //alert(this.id + ' ' + data[currId]);
            //alert($("#" + this.id + " option").size())
            $('#' + this.id).val(data[currId]);
            //alert(currId + ' ' + $('#' + this.id).val());
            //$('#' + this.id).bindSelect();
        }
    });
    $(id + 'input[type=checkbox]').each(function () {
        var currId = this.id.replace(prefix, "");
        if (currId == "Fiberdirection" && data.hasOwnProperty(currId)) {
            if (data[currId] == 'A') {
                $('#' + this.id).prop("checked", true);
            } else {
                $('#' + this.id).prop("checked", false);
            }
        }
    });
    var roughsType = $(id + 'input[type=radio][name=RoughsType]')
    if (data.hasOwnProperty("RoughsType") && roughsType.length == 4) {
        if (data["RoughsType"] == 'Y') {
            $(roughsType[0]).prop("checked", false);
            $(roughsType[1]).prop("checked", true);
            $(roughsType[2]).prop("checked", false);
            $(roughsType[3]).prop("checked", false);
        } else if (data["RoughsType"] == 'T') {
            $(roughsType[0]).prop("checked", false);
            $(roughsType[1]).prop("checked", false);
            $(roughsType[2]).prop("checked", true);
            $(roughsType[3]).prop("checked", false);
        } else if (data["RoughsType"] == 'L') {
            $(roughsType[0]).prop("checked", false);
            $(roughsType[1]).prop("checked", false);
            $(roughsType[2]).prop("checked", false);
            $(roughsType[3]).prop("checked", true);
        } else  if (data["RoughsType"] == 'K'){
            $(roughsType[0]).prop("checked", true);
            $(roughsType[1]).prop("checked", false);
            $(roughsType[2]).prop("checked", false);
            $(roughsType[3]).prop("checked", false);
        }
    }

    var isDisable = $(id + 'input[type=radio][name=IsDisable]')
    if (data.hasOwnProperty("IsDisable") && isDisable.length == 2) {
        if (data["IsDisable"] == '1') {
            $(isDisable[0]).prop('checked', false);
            $(isDisable[1]).prop('checked', true);
        } else {
            $(isDisable[0]).prop('checked', true);
            $(isDisable[1]).prop('checked', false);
        }
    }

}
function ifShowRoughcastSize() {
    var val = $("input[type='radio'][name='RoughsTypeRadio']:checked").val();
    //alert(val);
    if (val == 'Y' || val == 'L') {
        $('.category-0').hide();
        $('.category-1').show();
    } else {
        $('.category-1').hide();
        $('.category-0').show();
    }
}
function initBindSelect(id, prefix) {
    var searchArray = ["FProductionNO"]; /*"WasteUnit", "ProductUnit", "WasteWorkshop", "ProduWorkshop"*/
    if (id != '') { id = id + ' '; }
    prefix = prefix || '';
    $(id + 'select').each(function () {
        var currId = this.id.replace(prefix, "");
        //alert(this.id);
        //alert($.inArray(currId, searchArray));
        if ($.inArray(currId, searchArray) >= 0) {
            $('#' + this.id).bindSelect({ search: true });
        } else {
            $('#' + this.id).bindSelect({ search: false });
        }
    });
}

$.currentSubWindow = function () {
    var iframeId = top.$(".FriendStar_iframe:visible").attr("id");
    var subIframeId = top.frames[iframeId].$(".FriendStar_iframe:visible").attr("id");
    if (subIframeId == undefined || subIframeId == '') {
        return top.frames[iframeId];
    } else {
        return top.frames[iframeId].frames[subIframeId];
    }
}

$.currentSubSubWindow = function () {
    var iframeId = top.$(".FriendStar_iframe:visible").attr("id");
    var subIframeId = top.frames[iframeId].$(".FriendStar_iframe:visible").attr("id");
    var subSubIframeId = top.frames[iframeId].frames[subIframeId].$(".FriendStar_iframe:visible").attr("id");
    if (subSubIframeId == undefined || subSubIframeId == '') {
        return top.frames[iframeId].frames[subIframeId];
    } else {
        return top.frames[iframeId].frames[subIframeId].frames[subSubIframeId];
    }
}

function GUID() {
    this.date = new Date();   /* 判断是否初始化过，如果初始化过以下代码，则以下代码将不再执行，实际中只执行一次 */
    if (typeof this.newGUID != 'function') {   /* 生成GUID码 */
        GUID.prototype.newGUID = function () {
            this.date = new Date(); var guidStr = '';
            sexadecimalDate = this.hexadecimal(this.getGUIDDate(), 16);
            sexadecimalTime = this.hexadecimal(this.getGUIDTime(), 16);
            for (var i = 0; i < 9; i++) {
                guidStr += Math.floor(Math.random() * 16).toString(16);
            }
            guidStr += sexadecimalDate;
            guidStr += sexadecimalTime;
            while (guidStr.length < 32) {
                guidStr += Math.floor(Math.random() * 16).toString(16);
            }
            return this.formatGUID(guidStr);
        }
        /* * 功能：获取当前日期的GUID格式，即8位数的日期：19700101 * 返回值：返回GUID日期格式的字条串 */
        GUID.prototype.getGUIDDate = function () {
            return this.date.getFullYear() + this.addZero(this.date.getMonth() + 1) + this.addZero(this.date.getDay());
        }
        /* * 功能：获取当前时间的GUID格式，即8位数的时间，包括毫秒，毫秒为2位数：12300933 * 返回值：返回GUID日期格式的字条串 */
        GUID.prototype.getGUIDTime = function () {
            return this.addZero(this.date.getHours()) + this.addZero(this.date.getMinutes()) + this.addZero(this.date.getSeconds()) + this.addZero(parseInt(this.date.getMilliseconds() / 10));
        }
        /* * 功能: 为一位数的正整数前面添加0，如果是可以转成非NaN数字的字符串也可以实现 * 参数: 参数表示准备再前面添加0的数字或可以转换成数字的字符串 * 返回值: 如果符合条件，返回添加0后的字条串类型，否则返回自身的字符串 */
        GUID.prototype.addZero = function (num) {
            if (Number(num).toString() != 'NaN' && num >= 0 && num < 10) {
                return '0' + Math.floor(num);
            } else {
                return num.toString();
            }
        }
        /*  * 功能：将y进制的数值，转换为x进制的数值 * 参数：第1个参数表示欲转换的数值；第2个参数表示欲转换的进制；第3个参数可选，表示当前的进制数，如不写则为10 * 返回值：返回转换后的字符串 */GUID.prototype.hexadecimal = function (num, x, y) {
            if (y != undefined) { return parseInt(num.toString(), y).toString(x); }
            else { return parseInt(num.toString()).toString(x); }
        }
        /* * 功能：格式化32位的字符串为GUID模式的字符串 * 参数：第1个参数表示32位的字符串 * 返回值：标准GUID格式的字符串 */
        GUID.prototype.formatGUID = function (guidStr) {
            var str1 = guidStr.slice(0, 8) + '-', str2 = guidStr.slice(8, 12) + '-', str3 = guidStr.slice(12, 16) + '-', str4 = guidStr.slice(16, 20) + '-', str5 = guidStr.slice(20);
            return str1 + str2 + str3 + str4 + str5;
        }
    }
}

function onlyNumber(obj) {
    if ($(obj).attr("exception") != undefined && $(obj).attr("exception") != '') {
        if (obj.value == $(obj).attr("exception")) {
            return;
        }
    }

    obj.value = obj.value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
    obj.value = obj.value.replace(/^\./g, ""); //验证第一个字符是数字
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    //obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    var integral_length = 0;
    if ($(obj).attr("integral-length") != undefined && $(obj).attr("integral-length") != '') {
        integral_length = parseInt($(obj).attr("integral-length"));
    }
    var fractional_length = 0;
    if ($(obj).attr("fractional-length") != undefined && $(obj).attr("fractional-length") != '') {
        fractional_length = parseInt($(obj).attr("fractional-length"));
    }
    if (integral_length > 0 || fractional_length > 0) {
        var index = obj.value.indexOf('.');
        //alert(index);
        var array = obj.value.split('.');
        var integral = "";
        var fractional = "";
        if (array.length > 0) {
            integral = array[0];
        }
        if (array.length > 1) {
            fractional = array[1];
        }
        if (integral_length > 0 && integral.length > integral_length) {
            integral = integral.substr(0, integral_length);
        }
        if (fractional_length > 0 && fractional.length > fractional_length) {
            fractional = fractional.substr(0, fractional_length);
        }
        obj.value = integral;
        if (index > -1) {
            obj.value = obj.value + '.';
        }
        if (fractional.length > 0) {
            obj.value = obj.value + fractional;
        }
    }    
}
function onlyDigital(obj) {
    if ($(obj).attr("exception") != undefined && $(obj).attr("exception") != '') {
        if (obj.value == $(obj).attr("exception")) {
            return;
        }
    }
    obj.value = obj.value.replace(/\D/gi, ""); //清除"数字"以外的字符
}
function onlyInteger(obj) {
    if ($(obj).attr("exception") != undefined && $(obj).attr("exception") != '') {
        if (obj.value == $(obj).attr("exception")) {
            return;
        }
    }
    var t = obj.value.charAt(0);
    obj.value = obj.value.replace(/\D/gi, ""); //清除"数字"以外的字符
    if (t == '-') {
        obj.value = '-' + obj.value;
    }
}
function onlyIsNumber(obj) {
    if ($(obj).attr("exception") != undefined && $(obj).attr("exception") != '') {
        if (obj.value == $(obj).attr("exception")) {
            return;
        }
    }

    var t = obj.value.charAt(0);
    obj.value = obj.value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
    obj.value = obj.value.replace(/^\./g, ""); //验证第一个字符是数字
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    //obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    var integral_length = 0;
    if ($(obj).attr("integral-length") != undefined && $(obj).attr("integral-length") != '') {
        integral_length = parseInt($(obj).attr("integral-length"));
    }
    var fractional_length = 0;
    if ($(obj).attr("fractional-length") != undefined && $(obj).attr("fractional-length") != '') {
        fractional_length = parseInt($(obj).attr("fractional-length"));
    }
    if (integral_length > 0 || fractional_length > 0) {
        var index = obj.value.indexOf('.');
        //alert(index);
        var array = obj.value.split('.');
        var integral = "";
        var fractional = "";
        if (array.length > 0) {
            integral = array[0];
        }
        if (array.length > 1) {
            fractional = array[1];
        }
        if (integral_length > 0 && integral.length > integral_length) {
            integral = integral.substr(0, integral_length);
        }
        if (fractional_length > 0 && fractional.length > fractional_length) {
            fractional = fractional.substr(0, fractional_length);
        }
        obj.value = integral;
        if (index > -1) {
            obj.value = obj.value + '.';
        }
        if (fractional.length > 0) {
            obj.value = obj.value + fractional;
        }
    }

    if (t == '-') {
        obj.value = '-' + obj.value;
    }
}


